/**
 * @file common/utils/commonUtils.js 通用工具级
 * @author zhanlong
 */

import u from 'underscore';

export function isBrowser() {
    return typeof window !== 'undefined';
}

export function getCookie(name, cookieText = '') {
    if (isBrowser()) {
        cookieText = document.cookie;
    }
    const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
    const arr = cookieText.match(reg);
    return arr ? decodeURIComponent(arr[2]) : '';
}

export function setCookie(name, value) {
    document.cookie = name + '=' + escape(value) + '; path=/';
}

export function removeCookie(name) {
    const value = getCookie(name);

    if (value) {
        const exp = new Date();
        exp.setTime(exp.getTime() - 10000);
        document.cookie = name + '=' + value + '; expires=' + exp.toGMTString() + '; path=/';
    }
}

export function getConfig(key = '', val = '', targets = [], parent = null) {
    let config;

    for (let i = 0, l = targets.length; i < l; i++) {
        let element = targets[i];

        if (element[key] === val) {
            config = {config: element, parent};
            break;
        }
        else if (u.isArray(element[key]) && u.contains(element[key], val)) {
            config = {config: element, parent};
            break;
        }
        else if (element.children && element.children.length) {
            parent = element;
            config = getConfig(key, val, element.children, parent);

            if (config) {
                break;
            }
        }
    }

    return config;
}

export function fill(template, data) {
    return u.template(template, {
        interpolate: /\{(.+?)\}/g
    })(data);
}

export function loadScript(url) {
    let scripts = document.getElementsByTagName('script');
    let script = u.findWhere(scripts, {src: url});

    if (script) {
        return Promise.resolve(script);
    }
    else {
        return new Promise((resolve, reject) => {
            script = document.createElement('script');
            script.src = url;
            document.getElementsByTagName('head')[0].appendChild(script);
            script.onload = e => resolve(script);
        });
    }
}

export function chunk(array, size) {
    size = Math.max(size, 0);

    /* eslint-disable */
    const length = array == null ? 0 : array.length;
    /* eslint-enable */

    if (!length || size < 1) {
        return [];
    }


    let index = 0
    let resIndex = 0
    const result = new Array(Math.ceil(length / size));

    while (index < length) {
        result[resIndex++] = Array.prototype.slice.call(array, index, (index += size));
    }

    return result;
}
